package cn.lyjuan.dwz_manage.core.java.action;


import cn.lyjuan.dwz_manage.core.base.pojo.ManagePojo;
import cn.lyjuan.dwz_manage.core.java.cst.DwzManageCst;
import cn.lyjuan.dwz_manage.core.java.dto.GroupActionBean;
import cn.lyjuan.dwz_manage.core.java.service.ActionService;
import cn.lyjuan.dwz_manage.core.java.service.ManageService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by chad on 2016/3/9.
 */
@Controller
public class IndexAction extends BaseAction
{
    private static Logger log = LogManager.getLogger(IndexAction.class.getName());

    @Autowired
    private DwzManageCst dwzManageCst;

    @Autowired
    @Qualifier("mgActionService")
    private ActionService actionSer;

    @Autowired
    @Qualifier("mgManageService")
    private ManageService manageSer;

    /**
     * 因为SpringSecurity登陆成功后是转发请求，所以这里加一个重定向<br />
     * 以使用用户刷新避免重新提交登陆表单
     * @return
     */
    @RequestMapping("toindex")
    public String toindex()
    {
        return "redirect:/index" + dwzManageCst.getHttpSuffix();
    }

    @RequestMapping("index")
    public void index(HttpServletRequest req)
    {
        ManagePojo manage = manageSer.queryManageByName(this.getUserName());

        // 获取权限信息
        List<GroupActionBean> actions = actionSer.queryActions(manage, true);

        req.setAttribute("actions", actions);
    }

    /**
     * 跳转JSP
     * @param path
     * @param viewName
     * @return
     */
    @RequestMapping("to/{path}/{viewName}")
    public String toJsp(@PathVariable String path, @PathVariable String viewName,
                        HttpServletResponse resp)
    {
        if (StringUtils.isEmpty(path)
                || StringUtils.isEmpty(viewName))
        {
            resp.setStatus(HttpStatus.NOT_FOUND.value());
            return Integer.toString(HttpStatus.NOT_FOUND.value());
        }

        // 参数不合法
        if (!path.matches("^[a-zA-Z0-9_]+$")
                || !viewName.matches("^[a-zA-Z0-9_]+$"))
        {
            resp.setStatus(HttpStatus.NOT_FOUND.value());
            return Integer.toString(HttpStatus.NOT_FOUND.value());
        }

        return path + "/" + viewName;
    }
}
